package com.ahcloud.edas.common.kafka;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @program: edas-common
 * @description:
 * @author: YuKai Fan
 * @create: 2024/4/20 10:42
 **/
@Slf4j
public class KafkaClientInstance {

    private final static KafkaClientInstance instance = new KafkaClientInstance();

    private KafkaClientInstance() {
    }

    /**
     * The container of the consumer in the current client. The key is the name of consumerGroup.
     */
    private final ConcurrentMap<String, KafkaConsumerInner> consumerTable = new ConcurrentHashMap<>();

    public static KafkaClientInstance getInstance() {
        return instance;
    }
    /**
     * 注册消费者
     * @param group
     * @param consumerInner
     * @return
     */
    public synchronized boolean registerConsumer(final String group, final KafkaConsumerInner consumerInner) {
        if (group == null || consumerInner == null) {
            return false;
        }
        KafkaConsumerInner prev = this.consumerTable.putIfAbsent(group, consumerInner);
        if (prev != null) {
            log.warn("the consumer group[{}] exist already.", group);
            return false;
        }
        return true;
    }

    public void doConsumerStart() {
        for (Map.Entry<String, KafkaConsumerInner> entry : consumerTable.entrySet()) {
            KafkaConsumerInner consumerInner = entry.getValue();
            consumerInner.consumerStart();
        }
    }

    public void doConsumerStop() {
        for (Map.Entry<String, KafkaConsumerInner> entry : consumerTable.entrySet()) {
            KafkaConsumerInner consumerInner = entry.getValue();
            consumerInner.consumerShutdown();
        }
    }

}
